package com.net.xpay.core.helper;

import com.google.common.base.Strings;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.common.util.SerializationUtil;
import com.net.xpay.core.CoreProperties;
import com.net.xpay.core.helper.sms.chuanglan.chuanglan.ChuanglanSendUtil;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 2019/2/25 15:20
 * <p>
 * 发短信
 */
@Slf4j
@Component
public class SmsHelper {

    @Autowired
    private CoreProperties coreProperties;

    private static YunpianClient client = null;

    public static int countSms(String smsContent) {//短信记数
        if (Strings.isNullOrEmpty(smsContent)) {
            return 0;
        }

        int length = smsContent.length();

        int count = 1;
        if (length > 70) {
            count = (length + 66) / 67;
        }
        return count;
    }

    public synchronized void init() {
        if (client != null) {
            return;
        }
        client = new YunpianClient(coreProperties.getSoftSmsAppkey()).init();
    }

//    public void sendSms(String mobile, String content) {
//        log.info("sendSms mobile={}|content={}", mobile, content);
//        if (client == null) {
//            init();
//        }
//
//        try {
//            //发送短信API
//            Map<String, String> param = client.newParam(2);
//            param.put(YunpianClient.MOBILE, mobile);
//            param.put(YunpianClient.TEXT, content);
//            //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
//            //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
//            Result<SmsSingleSend> result = client.sms().single_send(param);
//            log.info(SerializationUtil.obj2String(result));
//        } catch (Exception e) {
//            log.error("sendSms error|mobile={}|content={}", mobile, content, e);
//            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "短信发送发生未知异常，请稍后再试");
//        }
//    }

    public void sendSms(String mobile, String content) {
        log.info("sendSms mobile={}|content={}", mobile, content);
        try {
            //发送短信API
            ChuanglanSendUtil util = new ChuanglanSendUtil();
            util.sendMsgByCL(mobile, content, 0);
        } catch (Exception e) {
            log.error("sendSms error|mobile={}|content={}", mobile, content, e);
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "短信发送发生未知异常，请稍后再试");
        }
    }
}
